package com.hulk.dryad.manage.boot.respone;

import com.hulk.dryad.common.annotation.RespData;
import com.hulk.dryad.common.annotation.RespExcel;
import com.hulk.dryad.common.annotation.RespSha256;
import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.BEC;
import com.hulk.dryad.common.exception.BaseRteException;
import com.hulk.dryad.manage.boot.basic.error.BaseExceptionTranslator;
import com.hulk.dryad.manage.security.component.DryadAccessDeniedHandler;
import com.hulk.dryad.manage.security.component.DryadAuthExceptionEntryPoint;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.firewall.RequestRejectedException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


import javax.validation.ConstraintViolationException;
import java.lang.reflect.Method;


/**
 * @author hulk
 * @date 2019/10/17
 * 重写返回体,全局业务异常拦截。
 */
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE-1)
@RestControllerAdvice(basePackages = "com.hulk.dryad")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class ResponseDataBodyAdvice extends BaseExceptionTranslator implements ResponseBodyAdvice<Object> {


	/** 类上或者方法上是否有RespResult注解，有进行如下处理，没有直接返回。*/
	@Override
	public boolean supports(MethodParameter returnType, Class converterType) {
		Method method = returnType.getMethod();
		boolean isMethodRespExcelAnnotated = AnnotatedElementUtils.isAnnotated(method, RespExcel.class);
		if(isMethodRespExcelAnnotated){
			return false;
		}
		boolean isMethodRespSha256Annotated = AnnotatedElementUtils.isAnnotated(method, RespSha256.class);
		if(isMethodRespSha256Annotated){
			return false;
		}
		boolean isMethodRespDataAnnotated = AnnotatedElementUtils.isAnnotated(method, RespData.class);
		if(isMethodRespDataAnnotated&& (!isMethodRespSha256Annotated )){
			return true;
		}
		Class<?> targetClass = method.getDeclaringClass();
	    boolean isClazzRespSha256Annotated	= AnnotatedElementUtils.isAnnotated(targetClass, RespSha256.class);
		if(isClazzRespSha256Annotated){
			return false;
		}
		boolean isClazzRespDataAnnotated	= AnnotatedElementUtils.isAnnotated(targetClass, RespData.class);
		if(isClazzRespDataAnnotated&& (!isClazzRespSha256Annotated )){
			return true;
		}
		return false;
	}

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

		if (body == null) {
			return null;
		}
        if (body instanceof R<?>) {
            return body;
        }
        if (body instanceof BEC) {
			BEC bec = (BEC) body;
			if(bec==BEC.S0){
				return  R.ok();
			}else {
				return  R.failed(bec.getErrCode(), bec.getErrDesc());
			}
        }
        return R.ok(body);
    }

    @ExceptionHandler(BaseRteException.class)
	@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
    public R<Object> handleError(BaseRteException e) {
        log.error("业务异常:[{}]", e.getMessage());
        return  R.failed(e.getErrCode(), e.getErrDesc());
    }
	@ExceptionHandler(AccessDeniedException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleError(AccessDeniedException e) {
		log.error("拒绝授权异常信息 :[{}]",e.getMessage());
		return DryadAccessDeniedHandler.accessDenied2R(e);
	}
	@ExceptionHandler(AuthenticationException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R<Object> handleError(AuthenticationException e) {
		log.error("登录账号认证失败:[{}]", e.getMessage());
		return DryadAuthExceptionEntryPoint.authException2R(e);
	}
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(MethodArgumentNotValidException e) {
		log.error("参数验证失败:[{}]", e.getMessage());
		return handleError(e.getBindingResult());
	}
	@ExceptionHandler(BindException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(BindException e) {
		log.error("参数绑定失败:[{}]", e.getMessage());
		return handleError(e.getBindingResult());
	}
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(ConstraintViolationException e) {
		log.error("参数验证失败:[{}]", e.getMessage());
		return handleError(e.getConstraintViolations());
	}
	@ExceptionHandler(MissingServletRequestParameterException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(MissingServletRequestParameterException e) {
		log.error("缺少请求参数:[{}]", e.getMessage());
		String message = String.format("缺少必要的请求参数: %s", e.getParameterName());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message);
	}
	@ExceptionHandler(MethodArgumentTypeMismatchException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(MethodArgumentTypeMismatchException e) {
		log.error("请求参数格式错误:[{}]", e.getMessage());
		String message = String.format("请求参数格式错误: %s", e.getName());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message);
	}
	@ExceptionHandler(HttpMessageNotReadableException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public R<Object> handleError(HttpMessageNotReadableException e) {
		log.error("消息不能读取:[{}]", e.getMessage());
		return  R.failed(BEC.E_6003.getErrCode(),BEC.E_6003.getErrDesc()+":"+e.getMessage());
	}
	@ExceptionHandler(NoHandlerFoundException.class)
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public R<Object> handleError(NoHandlerFoundException e) {
		log.error("404没找到请求:[{}]", e.getMessage());
		return  R.failed(BEC.E_4004.getErrCode(),BEC.E_4004.getErrDesc()+":"+e.getMessage());
	}
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	public R<Object> handleError(HttpRequestMethodNotSupportedException e) {
		log.error("405不支持当前请求方法:[{}]", e.getMessage());
		return  R.failed(BEC.E_4005.getErrCode(),BEC.E_4005.getErrDesc()+":"+e.getMessage());
	}
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	public R<Object> handleError(HttpMediaTypeNotSupportedException e) {
		log.error("不支持当前媒体类型:[{}]", e.getMessage());
		return  R.failed(BEC.E_4015.getErrCode(),BEC.E_4015.getErrDesc()+":"+e.getMessage());
	}
	@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	public R<Object> handleError(HttpMediaTypeNotAcceptableException e) {
		String message = e.getMessage() + " " + StringUtils.collectionToCommaDelimitedString(e.getSupportedMediaTypes());
		log.error("不接受的媒体类型:[{}]", message);
		return  R.failed(BEC.E_4015.getErrCode(),BEC.E_4015.getErrDesc()+":"+message);
	}
	@ExceptionHandler(DuplicateKeyException.class)
	@ResponseStatus(HttpStatus.INSUFFICIENT_STORAGE)
	public R<Object> handleError(DuplicateKeyException e) {
		log.error("数据库行字段重复:[{}]", e.getMessage());
		return   R.failed(BEC.E_6001.getErrCode(),BEC.E_6001.getErrDesc()+":"+e.getMessage()) ;
	}
	@ExceptionHandler(MyBatisSystemException.class)
	@ResponseStatus(HttpStatus.INSUFFICIENT_STORAGE)
	public R<Object> handleError(MyBatisSystemException e) {
		log.error("持久层异常:[{}]", e.getMessage());
		return R.failed(BEC.E_5000.getErrCode(),BEC.E_5000.getErrDesc()+":"+e.getMessage());
	}
	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.EXPECTATION_FAILED)
	public R<Object> handleError(Exception e) {
		log.error("unknow Exception", e);
		return    R.failed(BEC.E_9999.getErrCode(),BEC.E_9999.getErrDesc()+":"+e.getMessage()) ;
	}
	@DeleteMapping("/error")
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public R noHandlerFoundException() {
		return R.failed(HttpStatus.NOT_FOUND.getReasonPhrase());
	}
}
